<template>
  <div>
    <!-- 头部面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            v-model="queryInfo.query"
            placeholder="请输入内容"
            class="input-with-select"
            clearable
            @clear="getUserList"
          >
            <el-button @click="searchUserByName" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click.prevent="addDialogVisible = true;">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="userList" stripe border>
        <el-table-column label="#">
          <template
            slot-scope="scope"
          >{{scope.$index+(queryInfo.pagenum - 1) * queryInfo.pagesize + 1}}</template>
        </el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="mobile" label="手机"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="140px"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="create_time" label="创建时间"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              @change="userStateChanged(scope.row)"
              v-model="scope.row.mg_state"
              active-color="#409EFF"
              inactive-color="#909399"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="修改" placement="top" :enterable="false">
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="showEditDialog(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="delUser(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                size="mini"
                type="warning"
                icon="el-icon-setting"
                @click="showRolesDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分配角色对话框 -->
      <el-dialog title="提示" :visible.sync="userRoledialogVisible" width="50%" @close="setRoleClose">
        <div>
          <p>当前的用户: {{userInfo.username}}</p>
          <p>当前的角色: {{userInfo.role_name}}</p>
          <p>
            分配新角色：
            <el-select v-model="selectedRoleId" placeholder="请选择">
              <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              ></el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="userRoledialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveRole()">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分页区 -->
      <el-pagination
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :current-page="queryInfo.pagenum"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
      <!-- 添加用户对话框 -->
      <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose">
        <!-- 内容主体 -->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password" type="password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部内容区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户的对话框 -->
      <el-dialog
        title="修改用户"
        :visible.sync="updatedialogVisible"
        width="50%"
        @close="editDialogClose"
      >
        <el-form :model="addForm" :rules="addFormRules" ref="editFormRef" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="updatedialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUser">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rules, value, cb) => {
      const regMail = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
      if (!regMail.test(value)) {
        return cb(new Error("请输入合法的邮箱"));
      }
      return cb();
    };
    // 验证手机的规则
    var checkMobile = (rules, value, cb) => {
      const regMoblie = /^1[34578]\d{9}$/;
      if (!regMoblie.test(value)) {
        return cb(new Error("请输入合法的手机号"));
      }
      return cb();
    };
    return {
      userInfo: {},
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 5
      },
      userList: [],
      total: 0,
      addDialogVisible: false, // 控制添加用户对话框显示与隐藏
      updatedialogVisible: false, // 控制修改用户对话框显示与隐藏
      // 添加用户的表单数据
      addForm: {
        id: "",
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      // 添加表单的验证规则对象
      addFormRules: {
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur"
          },
          {
            min: 3,
            max: 10,
            message: "用户名长度在3~10个字符之间",
            trigger: "blur"
          }
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur"
          },
          {
            min: 6,
            max: 15,
            message: "用户名长度在6~15个字符之间",
            trigger: "blur"
          }
        ],
        email: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: "blur"
          },
          {
            validator: checkEmail,
            trigger: "blur"
          }
        ],
        mobile: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur"
          },
          {
            validator: checkMobile,
            trigger: "blur"
          },
          {
            validator: checkMobile,
            trigger: "change"
          }
        ]
      },
      userRoledialogVisible: false,
      roleList: [],
      selectedRoleId:''
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    setRoleClose(){
      this.selectedRoleId = ''
      this.userInfo = {}
    },
    // 保存用户的角色
    async saveRole(){
      if(!this.selectedRoleId) return this.$message.error('请选择要绑定的角色！')
      const {data: res} = await this.$http.put(`users/${this.userInfo.id}/role`,{rid: this.selectedRoleId})
      if(res.meta.status!==200) return this.$message.error(res.meta.msg)
      this.$message.success('更新成功')
      this.getUserList()
      this.userRoledialogVisible = false
    },
    // 展示用户角色对话框
    async showRolesDialog(userInfo) {
      this.userInfo = userInfo;
      // 在展示对话框之前，获取所有的角色列表
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) return this.$message.error("获取角色失败");
      this.roleList = res.data;
      console.log(this.roleList);
      this.userRoledialogVisible = true;
    },
    // 修改用户信息
    editUser() {
      this.$refs.editFormRef.validate(async vd => {
        if (!vd) return this.$message.error("输入验证无法通过");
        const { data: res } = await this.$http.put(
          "users/" + this.addForm.id,
          this.addForm
        );
        this.getUserList();
        this.updatedialogVisible = false;
        this.$message.success("修改成功");
      });
    },
    // 根据用户id删除用户
    delUser(Id) {
      this.$msbox
        .confirm("确认删除id为" + Id + "的用户吗?", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
        .then(async () => {
          const { data: res } = await this.$http.delete("users/" + Id);
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
          this.$message.success("删除成功!");
          this.getUserList();
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    // 展示编辑用户的对话框
    async showEditDialog(Id) {
      this.updatedialogVisible = true;
      const { data: res } = await this.$http.get("users/" + Id);
      if (!res.meta.status === 200) return this.$message.error(res.meta.msg);
      this.addForm = res.data;
    },
    addUser() {
      this.$refs.addFormRef.validate(async vd => {
        if (!vd) return this.$message.error("输入验证无法通过！");
        // 前台校验通过后，发送数据请求
        const { data: res } = await this.$http.post("users", this.addForm);
        console.log(res);
        if (!(res.meta.status === 201)) return this.$message.error("添加失败");
        this.getUserList();
        this.addDialogVisible = false;
        this.$message.success("添加成功");
      });
    },
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo
      });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      console.log(res);
      this.total = res.data.total;
      this.userList = res.data.users;
    },
    searchUserByName() {
      this.queryInfo.pagenum = 1;
      this.getUserList();
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    async userStateChanged(user) {
      const { data: res } = await this.$http.put(
        `users/${user.id}/state/${user.mg_state}`
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
    },
    // 监听用户对话框关闭的事件
    addDialogClose() {
      this.$refs.addFormRef.resetFields();
    },
    // 监听用户对话框关闭的事件
    editDialogClose() {
      this.$refs.editFormRef.resetFields();
    }
  }
};
</script>

<style lang='less' scoped>
</style>
